//
//  ZDAuthViewController.m
//  OCSinaWeiBo
//
//  Created by Apple on 15/10/29.
//  Copyright © 2015年 itcast. All rights reserved.
//

#import "ZDAuthViewController.h"
#import "ZDNetworkTool.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import "ZDUserAccount.h"
#import "ZDWelcomeViewController.h"

#define ZDNetworkToolInstance [ZDNetworkTool sharedInstance]

extern NSString *const ZDSwitchControllerNotification;

@interface ZDAuthViewController () <UIWebViewDelegate>

@property (nonatomic, strong) UIWebView *webView;

@end

@implementation ZDAuthViewController

- (void)loadView
{
    self.view = self.webView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"新浪微博";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(cancel)];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"填充" style:UIBarButtonItemStyleDone target:self action:@selector(auto_fill)];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    //加载请求  加载授权登录页面
    NSURLRequest *request = [NSURLRequest requestWithURL:[ZDNetworkToolInstance authURL]];
    [self.webView loadRequest:request];
}

#pragma mark - cancel按钮点击回调方法
- (void)cancel
{
    //移除提示框
    [SVProgressHUD dismiss];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

//填充按钮点击回调方法
- (void)auto_fill
{
    
    NSString *js = @"document.getElementById('userId').value='925462931@qq.com';document.getElementById('passwd').value='a910911804';";
    
    // webView执行js代码
    [self.webView stringByEvaluatingJavaScriptFromString: js];
}

/**
 *  请求失败调用
 */
- (void)loadFailWith:(NSString *)message
{
    [SVProgressHUD showErrorWithStatus:message maskType:SVProgressHUDMaskTypeBlack];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self cancel];
    });
}


#pragma mark - UIWebViewDelegate代理方法
/**
 *  webView开始加载调用
 */
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [SVProgressHUD showWithStatus:@"正在拼命加载..." maskType:SVProgressHUDMaskTypeBlack];
}

/**
 *  webView结束加载调用
 */
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    ZDLog(@"加载完成");
    //加载完后移除提示框
    [SVProgressHUD dismiss];
}

/**
 *  webView是否应该加载
 */
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    ZDLog(@"request = %@", request);
    
    /*
       加载登陆界面： https://api.weibo.com/oauth2/authorize?client_id=1671583110&redirect_uri=http://www.baidu.com/
       点击取消： http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
       点击授权：http://www.baidu.com/?code=606f86ca9ba1128eb1d802410428a8a1
     */
    
    NSString *urlString = request.URL.absoluteString;
    
    //过滤加载登录界面
    if (![urlString hasPrefix:@"http://www.baidu.com/"])
    {
        return YES;
    }
    
    //截取 ？后面的字符串
    NSString *queryStr = request.URL.query;
    
//    ZDLog(@"%@", queryStr);
    
    //判断 是否是以 "code=" 为前缀 只有点击授权 才有code返回
    NSString *prefixStr = @"code=";
    if ([queryStr hasPrefix:prefixStr])
    {
        //截取 code
        NSString *codeString = [queryStr substringFromIndex:prefixStr.length];
        
        ZDLog(@"点击授权code: %@", codeString);
        
        //获取accessToken(访问令牌)
        [self loadAccessToken:codeString];
    }
    
    //没有返回code 说明点击的取消 返回NO 表示不加载回调URL(这里设置的回调URL是http://www.baidu.com/) 即打开百度
    return NO;
}


#pragma mark - 抽取 加载accessToken 方法
- (void)loadAccessToken:(NSString *)codeString
{
    //获取accessToken(访问令牌)
    [ZDNetworkToolInstance loadAccessToken:codeString success:^(id responseObject) {
        
        ZDLog(@"responseObject: %@", responseObject);
        
        NSDictionary *result = (NSDictionary *)responseObject;
        
        //字典转模型
        ZDUserAccount *account = [ZDUserAccount userAccountWithDictionary:result];
        
        //保存用户账户模型
        [account saveUserAccount];
        
        //加载用户信息
        [account loadUserInfoWithSuccess:^(id responseObject) {
            
            ZDLog(@"responseObject: %@", responseObject);
            
            NSDictionary *userInfo = (NSDictionary *)responseObject;
            
            //保存用户昵称
            account.name = userInfo[@"name"];
            //保存用户头像
            account.avatar_large = userInfo[@"avatar_large"];
            
            //保存用户信息
            [account saveUserInfo];
            
            //移除提示框 并退出登录界面
            [self cancel];
            
            //登录成功，跳转到欢迎控制器
            [[NSNotificationCenter defaultCenter] postNotificationName:ZDSwitchControllerNotification object:self userInfo:@{@"class":[ZDWelcomeViewController class]}];
            
        } failure:^(NSError *error) {
            
            ZDLog(@"请求用户信息失败: %@", error);
            
            [self loadFailWith:@"网络不给力..."];
        }];
        
    } failure:^(NSError *error) {
        
        ZDLog(@"请求accessToken失败: %@", error);
        
        [self loadFailWith:@"网络不给力..."];
    }];

}


/**
 *  webView加载失败调用
 */
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    
}


#pragma mark 懒加载
- (UIWebView *)webView
{
    if (!_webView)
    {
        _webView = [[UIWebView alloc] init];
        
        _webView.delegate = self;
    }
    
    return _webView;
}


@end
